<?php

namespace App\Http\Controllers;

use App\Http\Model\ImgModel;
use App\Http\Model\NavModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class NavController extends Controller
{
    public function addNav(Request $req){

        $data = $this->getReqArray($req->getContent());

        $msg = $this->navValidator($data);

        if(!$msg)
        {
            return $this->getMsg(ERROR_CODE,$msg);
        }

        $navModel = new NavModel();

        $addRes = $navModel->addNav($data["position"],$data["navList"]);

        $res = array();

        if($addRes=="error"){
            return $this->getMsg(ERROR_CODE,"添加失败");
        }

        return $this->getMsg(SUCCESS_CODE,"添加成功");
    }

    public function selectNav($id){
        $navModel = new NavModel();

        $im = new ImgModel();

        preg_match('/^\d+$/', $id, $match);

        if(empty($match)){
            return $this->getMsg(ERROR_CODE,"ID不正确");
        }

        $selectRes = $navModel->selectNav($id);

        if(empty($selectRes)){
            return $this->getMsg(ERROR_CODE,$selectRes);
        }

        foreach($selectRes as $s){
            $s["picture"] = IMG_PATH.$s["img"]["file"];
            unset($s["img"]);
        }

        return $this->getData(SUCCESS_CODE,$selectRes);
    }

    private function navValidator($data){
        $validator = Validator::make($data,[
            "position"=>"required|integer",
            "navList"=>"required|array"
        ]);

        if($validator->fails()){
            return $validator->errors()->first();
        }

        return true;
    }
}
